<template>
  <div class="login-container"  >
    <div class="login-form-box">
      <div style="flex: 1;">
        <img src="@/assets/images/other/logo.png" alt="" style="width: 100%">
      </div>
      <div style="flex:1; display: flex; align-items: center; justify-content: center;">
        <el-form :v-model="user" style="width: 80%;">
          <div style="font-size: 20px; font-weight: bold; text-align: center;">欢迎登录酒店管理系统</div>
          <el-form-item prop="username">
            <el-input prefix-icon="el-icon-user" size="medium" placeholder="请输入账号"  v-model="user.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input prefix-icon="el-icon-lock" size="medium" show-password placeholder="请输入密码"  v-model="user.password"></el-input>
          </el-form-item>
          <el-form-item prop="validCode">
            <div style="display: flex;">
              <el-input prefix-icon="el-icon-circle-check" style="flex: 1;" v-model="user.code" size="medium"></el-input>
              <div style="flex:1 ;height: 36px;" @click="refreshCode">
                <dentify :identifyCode="identifyCode"></dentify>
              </div>
              <el-button 
                class="almost-transparent-btn"
                type="primary"
                size="mini"
                @click="handleClick"
              >
                --
              </el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%;" @click="login">登录</el-button>
          </el-form-item>
          <div style="display: flex;">
            <div style="flex: 1;">还没有账号?请<span style="color: #0f9876; cursor: pointer;" @click="$router.push('/register')">注册</span></div>
            <div style="flex: 1; text-align: right;"><span style="color: #0f9876; cursor: pointer;" @click="forgetPassword">忘记密码</span></div>
          </div>
           <!-- 忘记密码对话框 -->
      <el-dialog title="找回密码" :visible.sync="forgetDialogVisible" width="30%">
        <el-form :model="forgetForm" :rules="forgetRules" ref="forgetFormRef">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="forgetForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="forgetForm.phone" placeholder="请输入注册手机号"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="forgetForm.email" placeholder="请输入注册邮箱"></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input type="password" v-model="forgetForm.newPassword" show-password placeholder="请输入新密码"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input type="password" v-model="forgetForm.confirmPassword" show-password placeholder="请再次输入新密码"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="forgetDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForgetForm">确 定</el-button>
        </span>
      </el-dialog>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import Dentify from '@/components/dentify.vue';
import {MyLogin} from '@/api'
import { getToken,setToken,setAdmin,getAdmin,getUserId,setUserId } from '@/utils/auth.js';
import md5 from 'md5'; // 导入md5加密库
import {  listUser, updateUser } from '@/api/User.js';

export default{
  name:"Login",
  components:{
    Dentify,
  },
  data(){
     // 密码验证规则
    const validatePassword = (rule, value, callback) => {
      if (value !== this.forgetForm.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };
    return {
      
      
      identifyCodes: "1234567890abcdefjhijklinopqrsduvwxyz", //随机串内容,从这里随机抽几个显示验证码
      identifyCode: "", //验证码图片内容

      user:{
        username:'',
        password:'',
        code:''
      },

      // 忘记密码相关数据
      forgetDialogVisible: false,
      forgetForm: {
        username: '',
        phone: '',
        email: '',
        newPassword: '',
        confirmPassword: ''
      },
      forgetRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ]
      }
    }
  },
  created(){

  },mounted(){
    // 初始化验证码
    this.identifyCode = "";
    //参数：（1）随机串内容。（2）验证码显示位数
    this.makeCode(this.identifyCodes, 4);
  },
  methods:{
    handleClick() {
      console.log('透明按钮被点击了');
      this.user.code=this.identifyCode;
    },
    // 重置验证码
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    //获取验证码的值
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        //通过循环获取字符串内随机几位
        this.identifyCode +=
          this.identifyCodes[this.randomNum(0, this.identifyCodes.length)];
      }
    },
    //随机数字：用于当角标拿字符串的值
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    },
      async login(){
        console.log("验证码:", this.identifyCode);
        console.log("用户输入的验证码:",this.user.code);
        console.log('验证码是否正确:',this.identifyCode==this.user.code);
        // 表单校验
        if (!this.user.username) {
          this.$message.error('请输入用户名');
          return;
        }
        
        if (!this.user.password) {
          this.$message.error('请输入密码');
          return;
        }

        // 验证验证码
        if (this.identifyCode !== this.user.code) {
          this.$message.error('验证码错误');
          this.refreshCode(); // 刷新验证码
          return;
        }
         try {
          let res = await MyLogin({
            "username": this.user.username,
            "password": this.user.password
          });
          console.log(res);

          // 检查后端响应状态
          if (res.data.code === 1) {
            // 登录成功
            this.$message.success({
              message: '登录成功',
              duration: 2000 // 自定义展示时间，单位：毫秒
            });
            // 存储token或用户信息
          //localStorage.setItem('token', res.data.data.token);
          setToken(res.data.data.token);
           console.log(getToken());
           setUserId(res.data.data.id);
           console.log("当前登录用户id为："+getUserId());
            
           //设置是否为管理员
           if(res.data.data.isAdmin==1)setAdmin("true");
           else setAdmin("false");
            console.log("管理员状态"+getAdmin());


            // 跳转到首页或其他页面
            this.$router.push('/home');
          } else {
            // 登录失败
            this.$message.error(res.data.msg || '登录失败，请检查账号和密码');
            this.refreshCode(); // 刷新验证码
          }
        } catch (error) {
          console.error('登录请求失败:', error);
          this.$message.error('服务器错误，请稍后再试');
          this.refreshCode(); // 刷新验证码
        }
      },
       // 打开忘记密码对话框
    forgetPassword() {
      this.forgetDialogVisible = true;
      this.resetForgetForm();
    },
    // 重置忘记密码表单
    resetForgetForm() {
      this.forgetForm = {
        username: '',
        phone: '',
        email: '',
        newPassword: '',
        confirmPassword: ''
      };
      if (this.$refs.forgetFormRef) {
        this.$refs.forgetFormRef.resetFields();
      }
    },
    // 提交忘记密码表单
    async submitForgetForm() {
      this.$refs.forgetFormRef.validate(async (valid) => {
        if (!valid) return;
        
        try {
          // 获取所有用户数据
          const res = await listUser({ pageNum: 1, pageSize: 1000 });
          if (res.code !== 200) {
            this.$message.error('获取用户数据失败');
            return;
          }
          
          // 查找匹配的用户
          const matchedUser = res.rows.find(user => 
            user.username === this.forgetForm.username &&
            user.phone === this.forgetForm.phone &&
            user.email === this.forgetForm.email
          );
          
          if (!matchedUser) {
            this.$message.error('用户信息不匹配，请检查用户名、手机号和邮箱');
            return;
          }
          
          // 使用MD5加密新密码
          const encryptedPassword = md5(this.forgetForm.newPassword);
          
          // 准备更新数据
          const updateData = {
            id: matchedUser.id,
            password: encryptedPassword,
            // 保留其他字段不变
            username: matchedUser.username,
            phone: matchedUser.phone,
            email: matchedUser.email,
            status: matchedUser.status,
            isAdmin: matchedUser.isAdmin
          };
          
          // 调用更新接口
          const updateRes = await updateUser(updateData);
          if (updateRes.code === 200) {
            this.$message.success('密码修改成功');
            this.forgetDialogVisible = false;
          } else {
            this.$message.error(updateRes.msg || '密码修改失败');
          }
        } catch (error) {
          console.error('密码重置失败:', error);
          this.$message.error('密码重置失败，请稍后重试');
        }
      });
    }
  }
}
</script>

<style scoped>
  .login-container{
    background-color:#abd2ff;
    height: 100vh;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .login-form-box{
    background-color:white;
    height: 60vh;
    width: 50%;
    border-radius: 10px;
    overflow: hidden;
    display: flex;
    align-items: center;
  }

  /* 几乎透明的按钮样式 */
.almost-transparent-btn {
  /* 背景色透明度接近0（0.05非常淡） */
  background-color: rgba(64, 158, 255, 0.01) !important;
  /* 边框透明度也降低 */
  border-color: rgba(64, 158, 255, 0.1) !important;
  /* 文字颜色稍微淡一些 */
  color: rgba(64, 158, 255, 0.7) !important;
  /* 去掉默认阴影 */
  box-shadow: none !important;
}

/* 悬停效果 - 稍微增加一点透明度 */
.almost-transparent-btn:hover {
  background-color: rgba(64, 158, 255, 0.1) !important;
  border-color: rgba(64, 158, 255, 0.2) !important;
  color: rgba(64, 158, 255, 0.9) !important;
}

/* 点击效果 */
.almost-transparent-btn:active {
  background-color: rgba(64, 158, 255, 0.15) !important;
  border-color: rgba(64, 158, 255, 0.3) !important;
}

.transparent-button-demo {
  padding: 20px;
  background-color: #f5f7fa; /* 浅灰色背景，便于观察透明效果 */
}
</style>